#!/usr/bin/env python
#coding=UTF-8

import pygtk
import fileinput
import sys
import os.path
import gtk
import re

pygtk.require('2.0')

class QuickLaunch:

	def key_pressed(self, widget, event, *args):
		keyname = gtk.gdk.keyval_name(event.keyval).upper()
		if keyname == 'ESCAPE':
			gtk.main_quit()
		if keyname == 'TAB':
			if event.state & gtk.gdk.CONTROL_MASK:
				self.currentStore -= 1
			else:
				self.currentStore += 1
			
			self.currentStore%=len(self.treestore)
			self.treeview.set_model(self.treestore[self.currentStore])
			self.groupLabel.set_text(self.treestoreLabels[self.currentStore])

	def delete_event(self, widget, event, data=None):
		gtk.main_quit()
		return False

	def destroy(self, widget, data=None):
		gtk.main_quit()
		
	def row_actived(self, widget, row, col):
		model = widget.get_model()
		value = model[row][1]
		
		#replace markers
		i = 1
		for arg in sys.argv[1:]:
			value = value.replace("§" + str(i), arg)
			++i
		
		#remove any unmatched markers
		value = re.sub(r"§\d", "", value)
		
		#replace new lines and tabs
		value = value.replace("\\t", "\t")
		value = value.replace("\\n", "\n")
		
		# get the clipboard
		clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)		
		
		# update the clipboard
		clipboard.set_text(value)
		
		#exit
		gtk.main_quit()
		
	def __init__(self):
		#create and setup the window
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.set_size_request(200, 600)
		self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
		self.window.set_decorated(False)
		self.window.set_title("Clipboard Database")
		self.window.set_border_width(3)
		
		#link up events
		self.window.connect("delete_event", self.delete_event)
		self.window.connect("focus_out_event", self.delete_event)
		self.window.connect("key-press-event", self.key_pressed)

		# load entries from data.txt
		self.currentStore = 0
		self.treestore = list()
		self.treestoreLabels = list()
		self.treestore.append(gtk.TreeStore(str, str))
		self.treestoreLabels.append("Default")
		
		try:
			for line in fileinput.input(os.path.dirname(__file__) + "/data.txt"):
				# line can't be empty
				strippedLine = line.strip()
				if len(strippedLine) != 0:
					# find group markers
					if re.match(r"^---.*$", strippedLine):
						self.currentStore += 1
						self.treestore.append(gtk.TreeStore(str, str))
						self.treestoreLabels.append(strippedLine.replace("---", ""))
					# otherwise find standard entries
					else:				
						data = line.split('\t', 1)
						# line must have two parts separated by a tab
						if len(data) == 2:
							self.treestore[self.currentStore].append(None, [data[0].strip(), data[1].strip()])
		except:
			pass
   
 		# reset the current group - we will look at the default group first
		self.currentStore = 0
   
   		# create the GUI
		self.treeview = gtk.TreeView(self.treestore[self.currentStore])
		self.treeview.set_headers_visible(False)
		self.treeview.connect("row-activated", self.row_actived)

		self.tvcolumn = gtk.TreeViewColumn('Shortcut')
		self.treeview.append_column(self.tvcolumn)
		self.cell = gtk.CellRendererText()
		self.tvcolumn.pack_start(self.cell, True)
		self.tvcolumn.add_attribute(self.cell, 'text', 0)
		
		self.groupLabel = gtk.Label(self.treestoreLabels[self.currentStore])

		self.vbox = gtk.VBox()
		self.vbox.pack_start(self.groupLabel, False, False)
		self.vbox.pack_start(self.treeview)
    	
		self.window.add(self.vbox)
    
        # and the window
		self.window.show_all()

	def main(self):
        # All PyGTK applications must have a gtk.main(). Control ends here
        # and waits for an event to occur (like a key press or mouse event).
		gtk.main()

# If the program is run directly or passed as an argument to the python
# interpreter then create a HelloWorld instance and show it
if __name__ == "__main__":
	app = QuickLaunch()
	app.main()